package com.insyte.activities;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.ContextThemeWrapper;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.androidquery.AQuery;
import com.androidquery.callback.AjaxCallback;
import com.androidquery.callback.AjaxStatus;
import com.facebook.Profile;
import com.google.gson.Gson;
import com.insyte.R;
import com.insyte.config.Constants;
import com.insyte.config.InsyteApp;
import com.insyte.config.InsyteEnums;
import com.insyte.model.User;
import com.insyte.utils.Initialize;
import com.insyte.utils.ToastUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class LoginActivity extends ActionBarActivity implements View.OnClickListener {
    private EditText edt_email, edt_password;
    private TextView tv_new_account, tv_forgot_password;
    private Button btn_login, btn_back;
    private AQuery aQuery;
    private Map<String, Object> params;
    private String url_login = "";
    private String url_email = "/local/login";
    private String url_phone = "/register/phone";
    private InsyteEnums.TypeLogin loginEnum;
    private EditText edt_phone, edt_verify_code;
    private ImageView imgBack;
    ImageView imgLogo, imgDialogEmail;
    CheckBox chkSendUpdate;
    RelativeLayout btn_send_verification_code;
    TextView tv_prefix;
    RelativeLayout rlCountryCode;

    private Initialize initialize;
    private ProgressDialog progressDialog;
    private User user;
    private SharedPreferences prefs;
    private SharedPreferences.Editor editor;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        aQuery = new AQuery(this);
        prefs = getSharedPreferences(Constants.PREFS_NAME,MODE_PRIVATE);
        editor = prefs.edit();
        params = new HashMap<String, Object>();
        initialize = new Initialize(this);
        progressDialog = initialize.createProgressDialog("Loading");
        loginEnum = InsyteApp.getTypeLoginEnum(LoginActivity.this);
        switch (loginEnum) {
            case EMAIL:
                setContentView(R.layout.activity_login);
                url_login = Constants.URL_API + url_email;
                btn_back = (Button) findViewById(R.id.btn_back);
                btn_back.setOnClickListener(this);
                break;
            case PHONE:
                setContentView(R.layout.activity_login_phone);
                url_login = Constants.URL_API + url_phone;
                imgBack = (ImageView) findViewById(R.id.imgBack);
                imgBack.setOnClickListener(this);
                break;
            case FB:
                break;
        }

        getView();
        setEvent();
    }

    private void getView() {
        imgLogo = (ImageView) findViewById(R.id.imgLogo);
        switch (loginEnum) {
            case EMAIL:
                edt_email = (EditText) findViewById(R.id.edt_email);
                edt_password = (EditText) findViewById(R.id.edt_password);
                btn_login = (Button) findViewById(R.id.btn_login);
                tv_new_account = (TextView) findViewById(R.id.tv_new_account);
                tv_forgot_password = (TextView) findViewById(R.id.tv_forgot_password);
                break;
            case PHONE:
                chkSendUpdate = (CheckBox) findViewById(R.id.chkSendUpdate);
                edt_phone = (EditText) findViewById(R.id.edtPhoneNumber);
                tv_prefix = (TextView) findViewById(R.id.tv_prefix);
                btn_send_verification_code = (RelativeLayout) findViewById(R.id.btn_send_verification_code);
                rlCountryCode = (RelativeLayout) findViewById(R.id.rlCountryCode);
//                edt_verify_code = (EditText) findViewById(R.id.edt_verify_code);
                break;
            case FB:
                break;
        }
    }

    private void setEvent() {
        switch (loginEnum) {
            case EMAIL:
                btn_login.setOnClickListener(this);
                tv_new_account.setOnClickListener(this);
                tv_forgot_password.setOnClickListener(this);
                break;
            case PHONE:
                rlCountryCode.setOnClickListener(this);
                btn_send_verification_code.setOnClickListener(this);
                break;
            case FB:
                break;
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.tv_new_account:
                startActivity(new Intent(LoginActivity.this, RegisterActivity.class));
                break;
            case R.id.tv_forgot_password:
                startActivity(new Intent(LoginActivity.this, ForgotPasswordActivity.class));
                break;
            case R.id.btn_back:
                onBackPressed();
                break;
            case R.id.btn_login:
                runAjaxLogin();
                //startActivity(new Intent(LoginActivity.this, ProfileActivity.class));
                break;
            case R.id.rlCountryCode:
                showDialogSelectCountryCode();
                break;
            case R.id.btn_send_verification_code:
                runAjaxLogin();
                //showDialogSentVerifyCode();
                break;
            case R.id.imgBack :
                onBackPressed();
                break;
        }
    }

    private void showDialogSelectCountryCode() {
        AlertDialog.Builder builder = new AlertDialog.Builder(LoginActivity.this);
        builder.setTitle("Select country code");
        final CharSequence[] choiceList =
                {"US (+1)", "Vietnam (+84)", "Russia (+79)", "Vietnam (+84)", "US (+1)", "Vietnam (+84)",
                        "Russia (+79)", "Vietnam (+84)", "US (+1)", "Vietnam (+84)", "Russia (+79)", "Vietnam (+84)"};
        int selected = -1; // does not select anything
        builder.setSingleChoiceItems(choiceList, selected,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        ToastUtils.showToast(LoginActivity.this, "Select " + choiceList[which]);
                        tv_prefix.setText(choiceList[which]);
                        dialog.dismiss();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    private void runAjaxLogin() {
        if (initialize.checkNetwork()) {
            if (Check()) {
                progressDialog.show();
                switch (loginEnum) {
                    case EMAIL:
                        params.put("email", edt_email.getText().toString());
                        params.put("password", edt_password.getText().toString());
                        break;
                    case PHONE:
                        params.put("phone", edt_phone.getText().toString());
                        params.put("prefix", tv_prefix.getText().toString());
                        break;
                    case FB:
                        break;
                }
                aQuery.ajax(url_login, params, String.class, new AjaxCallback<String>() {
                    @Override
                    public void callback(String url, String result, AjaxStatus status) {
                        progressDialog.dismiss();
                        if (result != null) {
                            try {
                                JSONObject js = new JSONObject(result);
                                if (js.has("code")) {
                                    if (js.getInt("code") == 1) {
                                        Gson gson = new Gson();
                                        String jsData = js.getString("data");
                                        user = new User();
                                        user = gson.fromJson(jsData, User.class);
                                        //TODO save user to global or put intent
                                        InsyteApp.getInstance().saveUser(user);
                                        user.saveUserInformation(prefs);
                                        switch (loginEnum) {
                                            case EMAIL:
                                                startActivity(new Intent(LoginActivity.this, ProfileActivity.class));
                                                break;
                                            case PHONE:
                                                showDialogSentVerifyCode();
                                                //Thread.sleep(500L);
                                                Handler handler = new Handler();
                                                handler.postDelayed(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        //if (dialogSentVerify.isShowing())dialogSentVerify.dismiss();
                                                        startActivity(new Intent(LoginActivity.this, LoginVerifyPhoneActivity.class));
                                                    }
                                                }, 5000);
                                        }
                                        finish();
                                    }
                                    initialize.showToast(js.getString("message"));
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            initialize.showToast("check server");
                        }
                    }
                }.header("Content-Type", "application/x-www-form-urlencoded"));
            }
        } else {
            initialize.showToast("Please check your network!");
        }
    }

    Dialog dialogSentVerify;

    private void showDialogSentVerifyCode() {
        ContextThemeWrapper themedContext;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            themedContext = new ContextThemeWrapper(this, android.R.style.Theme_Holo_Light_Dialog_NoActionBar);
        } else {
            themedContext = new ContextThemeWrapper(this, android.R.style.Theme_Light_NoTitleBar);
        }
        dialogSentVerify = new Dialog(themedContext);
        dialogSentVerify.requestWindowFeature(Window.FEATURE_NO_TITLE); //before
        dialogSentVerify.setContentView(R.layout.dialog_code_sent);
        if (!dialogSentVerify.isShowing())
            dialogSentVerify.show();
        LinearLayout ln_sent_dialog = (LinearLayout)dialogSentVerify.findViewById(R.id.ln_sent_dialog);
        ln_sent_dialog.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (dialogSentVerify.isShowing())
                    dialogSentVerify.dismiss();
                startActivity(new Intent(LoginActivity.this, LoginVerifyPhoneActivity.class));
            }
        });


    }

    private boolean Check() {
        switch (loginEnum) {
            case EMAIL:
                if (!edt_email.getText().toString().equalsIgnoreCase("")) {
                    if (!isEmailValid(edt_email.getText().toString())) {
                        Toast.makeText(this, "Email is invalid.", Toast.LENGTH_LONG).show();
                        return false;
                    }
                }
                if (edt_email.getText().toString().equalsIgnoreCase("")) {
                    Toast.makeText(this, "Please enter your email.", Toast.LENGTH_LONG).show();
                    return false;
                }
                if (edt_password.getText().toString().equalsIgnoreCase("")) {
                    Toast.makeText(this, "Please enter your password", Toast.LENGTH_LONG).show();
                    return false;
                }
                break;
            case PHONE:
                if (edt_phone.getText().toString().equalsIgnoreCase("")) {
                    Toast.makeText(this, "Please enter your phone", Toast.LENGTH_LONG).show();
                    return false;
                }
                break;
        }
        return true;
    }

    public static boolean isEmailValid(String email) {
        if (Build.VERSION.SDK_INT >= 8) {
            return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
        }
        Pattern pattern;
        Matcher matcher;
        String EMAIL_PATTERN = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
        pattern = Pattern.compile(EMAIL_PATTERN);
        matcher = pattern.matcher(email);
        return matcher.matches();
    }
}
